package com.example.question.dp.dp3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 三角形最小路径和
 */
public class Code03_120 {
    public static void main(String[] args) {
        Code03_120 code = new Code03_120();
        List<Integer> l1 = Collections.singletonList(2);
        List<Integer> l2 = Arrays.asList(3, 4);
        List<Integer> l3 = Arrays.asList(6, 5, 7);
        List<Integer> l4 = Arrays.asList(4, 1, 8, 3);
        List<List<Integer>> l5 = Arrays.asList(l1, l2, l3, l4);
        System.out.println("code.minimumTotal(l5) = " + code.minimumTotal(l5));
    }


    public int minimumTotal1(List<List<Integer>> triangle) {
        // 这是上一层的和
        List<Integer> lastLevelMinSum = null;
        // 层次遍历
        for (List<Integer> list : triangle) {
            // 当前层的值
            if (lastLevelMinSum == null) {
                lastLevelMinSum = list;
            } else {
                List<Integer> tmp = new ArrayList<>();
                for (int j = 0; j < list.size(); j++) {
                    // 当前的值
                    Integer num = list.get(j);
                    int curSum;
                    if (j - 1 >= 0 && j <= lastLevelMinSum.size() - 1) {
                        curSum = num + Math.min(lastLevelMinSum.get(j), lastLevelMinSum.get(j - 1));
                    } else if (j == 0) {
                        curSum = num + lastLevelMinSum.get(j);
                    } else {
                        curSum = num + lastLevelMinSum.get(j - 1);
                    }
                    tmp.add(j, curSum);
                }
                lastLevelMinSum = tmp;
            }
        }
        int min = Integer.MAX_VALUE;
        for (Integer integer : lastLevelMinSum) {
            min = Math.min(integer, min);
        }
        return min;
    }

    public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[] dp = new int[n];
        for (int i = 0; i < n; i++) {
            dp[i] = triangle.get(n - 1).get(i);
        }
        for (int i = n - 2; i >= 0; i--) {
            for (int j = 0; j <= i; j++) {
                dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
            }
        }
        return dp[0];
    }

}
